<template>
  <div id="list">
    <div class="controls">
      <el-button color="#000" @click="loadData(1000)">加载1k条数据</el-button>
      <el-button color="#000" @click="loadData(10000)">加载1w条数据</el-button>
      <el-button color="#000" @click="scrollToIndex(500)">滚动到第500项</el-button>
    </div>
    <VirtualList
      ref="virtualListRef"
      class="list-container"
      :list-data="data"
      item-key="id"
      :estimated-item-size="120"
    >
      <template #default="{ item, index }">
        <div class="list-item">
          <img :src="item.avatar" alt="avatar" class="avatar">
          <div class="content">
            <div class="title">#{{ index }} - {{ item.name }}</div>
            <div class="description">{{ item.text }}</div>
          </div>
        </div>
      </template>
    </VirtualList>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import VirtualList from '@/components/auto/virtual-list.vue';
// 引入一个数据生成库，用于模拟真实数据
import { faker } from '@faker-js/faker';

interface ListItem {
  id: string;
  name: string;
  text: string;
  avatar: string;
}

const data = ref<ListItem[]>([]);
const virtualListRef = ref<InstanceType<typeof VirtualList> | null>(null);

const generateData = (count: number): ListItem[] => {
  const items: ListItem[] = [];
  for (let i = 0; i < count; i++) {
    const id = faker.string.uuid(); // 用 id 保证每次生成的图片是固定的
    items.push({
      id: id,
      name: faker.person.fullName(),
      text: faker.lorem.paragraph(Math.floor(Math.random() * 5) + 1),
      // 修复：使用一个稳定可靠的占位图服务
      avatar: `https://picsum.photos/seed/${id}/80/80`,
    });
  }
  return items;
};

const loadData = (count: number) => {
  data.value = generateData(count);
};

// 默认加载1000条数据
loadData(1000);


// 假设上面已经添加了 expose, 这里的调用就能工作
const scrollToIndex = (index: number) => {
  virtualListRef.value?.scrollToIndex(index);
};

</script>

<style scoped lang="less">
/* 全局样式 */
#list {
  height: 100vh;
  margin: 0;
  font-family: Avenir, Helvetica, Arial, sans-serif;
  display: flex;
  flex-direction: column;
}
.controls {
  padding: 10px;
  border-bottom: 1px solid #eee;
  flex-shrink: 0;
}
.controls button {
  margin-right: 10px;
  padding: 5px 10px;
}
.list-container {
  flex-grow: 1;
  border: 1px solid #ccc;
}
/* 列表项样式 */
.list-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eaeaea;
  box-sizing: border-box;
}
.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-right: 20px;
  flex-shrink: 0;
}
.content {
  display: flex;
  flex-direction: column;
}
.title {
  font-weight: bold;
  font-size: 18px;
  color: #333;
}
.description {
  margin-top: 8px;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}
</style>
